package com.elong.qadev.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;

import com.elong.qadev.entity.MenuItem;
import com.elong.qadev.entity.User;
import com.elong.qadev.model.MailInfo;
import com.elong.qadev.service.MenuServiceI;
import com.elong.qadev.service.UserServiceI;
import com.elong.qadev.tool.MD5ForLogin;
import com.elong.qadev.tool.MailUtil;
import com.elong.qadev.tool.StringUtils;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * @ClassName: LoginAction
 * @Description: TODO(登陆业务相关)
 * @author kangchen
 * @date 2015年9月8日
 *
 */
@ParentPackage("all")
public class LoginAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(LoginAction.class);
	@Autowired
	private UserServiceI userService;
	@Autowired
	private MenuServiceI menuService;
	private User user;
	private String verifyCode;

	public String getVerifyCode() {
		return verifyCode;
	}

	public void setVerifyCode(String verifyCode) {
		this.verifyCode = verifyCode;
	}

	private ArrayList<MenuItem> menuList = new ArrayList<MenuItem>();

	public ArrayList<MenuItem> getMenuList() {
		return menuList;
	}

	public void setMenuList(ArrayList<MenuItem> menuList) {
		this.menuList = menuList;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public LoginAction() {
		super();
	}

	/**
	 * 
	 * @Title: mailCheck
	 * @Description: TODO(校验邮箱是否重复)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "mailCheck", results = {})
	public String mailCheck() {
		logger.info("- 开始邮箱重复校验");
		if (userService.getSigleUser(user.mail) != null) {
			try {
				ServletActionContext.getResponse().getWriter().print("true");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 
	 * @Title: register
	 * @Description: TODO(注册数据保存)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "register", results = {
			@Result(name = "success", location = "/login.jsp", type = "dispatcher"),
			@Result(name = "input", location = "/user/new_account.jsp", type = "dispatcher") })
	public String register() {
		logger.info("- 开始提交注册");
		User u = new User();
		if (userService.getSigleUser(user.mail) != null) {
			logger.info("已经存在相同注册mail" + user.mail);
			return "input";
		} else {
			u.setMail(user.mail);
			u.setName(user.name);
			u.setPassword(MD5ForLogin.MD5(user.password));
			u.setPhoneNumber(user.phoneNumber);
			u.setCreatedatetime(new Date());
			logger.info("通过重复检验，存入数据库用户信息为：" + u.toString());
			userService.save(u);
			Map<String, Object> session;
			session = ActionContext.getContext().getSession();
			session.put("login_msg", "注册成功");
			return "success";
		}

	}

	/**
	 * 
	 * @Title: login
	 * @Description: TODO(登陆校验保存user进sessions)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "login", results = {
			@Result(name = "success", location = "/frame/mainFrame.jsp", type = "dispatcher"),
			@Result(name = "input", location = "/login.jsp", type = "redirect") })
	public String login() {
		logger.info("- 开始登陆校验");
		User u = null;
		Map<String, Object> session;
		session = ActionContext.getContext().getSession();
		if (session.get("user") != null) {
			menuList = menuService.getMenus();
			return "success";
		}
		if (userService.getSigleUser(user.mail) != null) {
			u = userService.getSigleUser(user.mail);
			logger.info("存储password为：" + u.password + "-----" + "输入password为："
					+ MD5ForLogin.MD5(user.password));
		}
		if ((u != null) && (u.password.equals(MD5ForLogin.MD5(user.password)))) {
			logger.info("执行登陆操作，存储session等信息");
			menuList = menuService.getMenus();
			logger.info("############################菜单信息传递成功："
					+ menuList.toString());
			session.put("user", u);
			return "success";
		} else {
			logger.info("登陆验证错误，执行错误提示");
			session.put("login_msg", "登陆账户或密码错误，请重新输入");
			return "input";
		}
	}

	/**
	 * 
	 * @Title: logOut
	 * @Description: TODO(注销登录功能)
	 * @param @return 参数
	 * @return String 返回类型
	 * @throws
	 */
	@Action(value = "loginOut", results = { @Result(name = "input", location = "/login.jsp", type = "redirect") })
	public String logOut() {
		ActionContext.getContext().getSession().clear();
		return "input";
	}

	/**
	 * 
	 * @Title: passwordUpdate
	 * @Description: TODO(修改更新密码)
	 * @param @throws Exception 参数
	 * @return void 返回类型
	 * @throws
	 */
	@Action(value = "passwordUpdate")
	public void passwordUpdate() throws Exception {
		String password = MD5ForLogin.MD5(user.password);
		logger.info("传入的密码是：" + password);
		User u = (User) ActionContext.getContext().getSession().get("user");
		u.setPassword(password);
		userService.updatePassword(u);
	}

	@Action(value = "phoneNumberUpdate")
	public void phoneUpdate() throws Exception {
		String phoneNumber = user.phoneNumber;
		logger.info("传入的手机号码是：" + phoneNumber);
		User u = (User) ActionContext.getContext().getSession().get("user");
		u.setPhoneNumber(phoneNumber);
		userService.updatePhoneNumber(u);
	}

	@Action(value = "pwdUpdate")
	public void pwdUpdate() {
		String mail = user.getMail();
		String code = verifyCode;
		String msg = "保存成功";
		String newPwd = StringUtils.getRandomStringByNumber(8);
		logger.info("pwdUpdate传入的值是：" + mail + " - " + code);
		String s_verifyCode = (String) ActionContext.getContext().getSession()
				.get("verifyCode");
		logger.info("session中存放的值是："+s_verifyCode);
		User u = userService.getSigleUser(mail);
		if (!code.equalsIgnoreCase(s_verifyCode)) {
			msg = "验证码错误，请重新输入。";
		} else {
			if (u == null) {
				msg = "此邮箱不存在，请注册。";
			} else {
				u.setPassword(MD5ForLogin.MD5(newPwd));
				userService.updatePassword(u);
				MailInfo mailInfo = null;
				try {
					mailInfo = new MailInfo();
				} catch (Exception e) {
					logger.info("邮件信息初始化失败，请检查配置文件");
					e.printStackTrace();
				}
				mailInfo.setToAddress(mail);
				mailInfo.setSubject("重置密码-(来自TI)");
				logger.info("邮件发送信息是：" + mailInfo.toString());
				mailInfo.setContent("您的新密码是："+newPwd+",请妥善保管，谢谢。");
				try{
					MailUtil.sendHtmlMail(mailInfo);			
				}catch(Exception e){
					logger.info("邮件发送失败，发生异常："+e.getStackTrace().toString());
				}
				msg = "您的密码已经通过邮件发送至您的邮箱，请注意查收。";
			}
		}
				
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		out.print(msg);
		out.flush();
		out.close();
	}
}
